﻿namespace Jhong.FunMVC
{
    using Microsoft.Owin;
    using System.Threading.Tasks;

    internal class RouteHandler
    {
        private IOwinContext _context;

        internal RouteHandler(IOwinContext context)
        {
            this._context = context;
            //TransformRoute();
        }

        public Task Hand()
        {
            var url = this._context.Request.Uri.AbsolutePath;
            RouteBase routeBase = null;
            foreach (var route in RouteTable.Routes)
            {
                if (route.IsMatch(url))
                {
                    routeBase = route;
                    break;
                }
            }
            var response = new Response(this._context.Response);
            if (null == routeBase)
            {
                ThrowExceptionHandler.ThrowException(null, response, new PageNotFoundException(), "", url);
                return CompletionTask.CompleteTask;
            }
            this._context.Request.QueryString = routeBase.TransformRouteParameter(this._context.Request);
            var request = new Request(this._context.Request, routeBase);
            return this.Execute(routeBase, request, response);
        }

        internal Task Execute(RouteBase routeBase, Request request, Response response)
        {
            var mvcHandler = new MVCHandler(routeBase, request, response);
            return mvcHandler.Hand();
        }

        private Microsoft.Owin.QueryString TransformRoute()
        {
            var localPath = this._context.Request.Uri.LocalPath;

            return new Microsoft.Owin.QueryString();
        }
    }
}